import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
import matplotlib.font_manager as fm

# 设置 matplotlib 字体支持中文
plt.rcParams['font.family'] = 'SimHei'  # 使用黑体字体
plt.rcParams['axes.unicode_minus'] = False  # 解决负号显示问题

class PieChart:
    def __init__(self, stats_window):
        self.stats_window = stats_window
        self.fig = None
        self.canvas = None
        self.ax = None

    def create_chart(self):
        self.fig = plt.Figure()
        self.ax = self.fig.add_subplot(111)
        self.canvas = FigureCanvas(self.fig)
        self.stats_window.setCentralWidget(self.canvas)

    def update_chart(self, send_ledger, receive_ledger):
        total_send = sum(r['amount'] for r in send_ledger.records)
        total_receive = sum(r['amount'] for r in receive_ledger.records)

        labels = ['随礼', '收礼']
        sizes = [total_send, total_receive]

        if self.ax:
            # 清空之前的绘图
            self.ax.clear()
            # 绘制新的饼图
            self.ax.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90, pctdistance=0.85, wedgeprops=dict(width=0.3))
            self.ax.axis('equal')
            self.ax.set_title('随礼与收礼比例')
            # 更新画布
            self.canvas.draw()